package com.tengju.user.application.archives;

import com.google.common.collect.Lists;
import com.tengju.user.application.shared.ApplicationException;
import com.tengju.user.application.shared.ApplicationExceptionCode;
import com.tengju.user.domain.model.survey.*;
import com.tengju.user.domain.model.user.UserIdCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ArchiveService {

    private SurveyRepotiory surveyRepotiory;

    @Autowired
    public ArchiveService(SurveyRepotiory surveyRepotiory) {
        this.surveyRepotiory = surveyRepotiory;
    }

    public List<SurveyQuestionResult> getFilledOption(SurveyId surveyId, UserIdCode idCode) {

        SurveyContent archiveContent = surveyRepotiory.getContent(idCode, surveyId);

        return Optional.ofNullable(archiveContent)
                .map(SurveyContent::getQuestionResults).orElse(Lists.newArrayList());

    }

    public Boolean submit(SurveyContent surveyContent) {

        SurveyConfig config = surveyRepotiory.getConfigById(surveyContent.getSurveyId().getValue());
        if (config == null || CollectionUtils.isEmpty(config.getQuestionConfigList())) {
            throw ApplicationException.error(ApplicationExceptionCode.INVALID_DATA,"未找到对应配置项");
        }

        //校验必填参数
        List<String> requiredCode = config.getQuestionConfigList().stream()
                .filter(surveyQuestionConfig -> surveyQuestionConfig.getRequired() == SurveyQuestionRequireEnum.REQUIRED)
                .map(SurveyQuestionConfig::getCode)
                .collect(Collectors.toList());

        Map<String, String> result = surveyContent.getQuestionResults().stream()
                .collect(Collectors.toMap(SurveyQuestionResult::getQuestionCode, SurveyQuestionResult::getQuestionContent));

        for (String code : requiredCode) {
            String content = result.get(code);
            if (StringUtils.isEmpty(content)) {
                throw ApplicationException.error(ApplicationExceptionCode.INVALID_DATA,"必填参数为空");
            }
        }
        return surveyRepotiory.saveSurveyContent(surveyContent);

    }

    public Boolean saveConfig(SurveyConfigInfo surveyConfigInfo) {
        return surveyRepotiory.saveSurveyConfig(surveyConfigInfo);
    }

    public Boolean updateConfig(Long id,SurveyConfigInfo surveyConfigInfo) {
        return surveyRepotiory.updateSurveyConfig(id,surveyConfigInfo);
    }

}
